package q1.project.web.interceptor;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.lang.NonNull;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import q1.project.modules.system.tenant.filter.TenantFilterManager;

/**
 * 租户过滤器拦截器 在请求开始时自动启用 Hibernate Filter，实现透明的租户数据隔离
 *
 * <p>执行顺序：
 *
 * <ol>
 *   <li>TenantInterceptor：解析并设置租户上下文（X-Tenant-Id、子域名等）
 *   <li>TenantFilterInterceptor：根据租户上下文启用 Hibernate Filter
 *   <li>业务逻辑：所有 JPA 查询自动应用租户过滤条件
 * </ol>
 *
 * @author Q1 Team
 * @version 1.0
 */
@Component
public class TenantFilterInterceptor implements HandlerInterceptor {

  private static final Logger log = LoggerFactory.getLogger(TenantFilterInterceptor.class);

  private final TenantFilterManager tenantFilterManager;

  public TenantFilterInterceptor(TenantFilterManager tenantFilterManager) {
    this.tenantFilterManager = tenantFilterManager;
  }

  @Override
  public boolean preHandle(
      @NonNull HttpServletRequest request,
      @NonNull HttpServletResponse response,
      @NonNull Object handler) {
    try {
      // 租户上下文已由 TenantInterceptor 设置
      // 这里启用 Hibernate Filter
      boolean tenantFilterEnabled = tenantFilterManager.enableTenantFilter();
      boolean softDeleteFilterEnabled = tenantFilterManager.enableSoftDeleteFilter();

      if (!tenantFilterEnabled) {
        // 某些接口可能不需要租户信息（如公开API、健康检查等）
        log.trace("租户过滤器未启用（租户ID为空），请求路径: {}", request.getRequestURI());
      } else {
        log.debug(
            "过滤器已启用 [租户:{}, 软删除:{}]，请求路径: {}",
            tenantFilterEnabled,
            softDeleteFilterEnabled,
            request.getRequestURI());
      }

      return true;
    } catch (Exception e) {
      log.error("启用租户过滤器失败，请求路径: {}", request.getRequestURI(), e);
      // 继续执行，让后续逻辑处理（如果没有租户过滤器，某些查询可能返回空结果）
      return true;
    }
  }

  @Override
  public void afterCompletion(
      @NonNull HttpServletRequest request,
      @NonNull HttpServletResponse response,
      @NonNull Object handler,
      Exception ex) {
    try {
      // 请求结束后清理所有 Filter
      tenantFilterManager.disableTenantFilter();
      tenantFilterManager.disableSoftDeleteFilter();
      log.trace("过滤器已清理，请求路径: {}", request.getRequestURI());
    } catch (Exception e) {
      log.warn("禁用过滤器失败，请求路径: {}", request.getRequestURI(), e);
    }
  }
}
